package com.common.zrd.mark;

import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import javax.swing.*;
import java.awt.*;
import java.io.FileOutputStream;

/**
 * @author zrd
 * @version 1.0
 * @date 2020/9/16 14:31
 */
public class PdfMarkUtils {
    private static int interval = 30;

    public static void main(String[] args) throws Exception {
        waterMark("D:/2.pdf", "D:/24.pdf", "18865598755");
        //addPdfMark("xxx.mark","image.png","yyy.xml");
        System.out.println("结束");
    }

    public static void waterMark(String inputFile, String outputFile, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //这里的字体设置比较关键，这个设置支持中文的写法
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);  //使用系统字体
            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            //设置透明度
            gs.setFillOpacity(0.3f);
            gs.setStrokeOpacity(0.3f);
            int total = reader.getNumberOfPages() + 1;
            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 0;
            int textW = 0;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight();
            textW = metrics.stringWidth(label.getText());
            PdfContentByte under;
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, 30); //控制字体间宽度
                // 水印文字成30度角倾斜
                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 16) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 8) {
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW,
                                height - textH, 30);
                    }
                }
                // 添加水印文字
                under.endText();
            }
            //关闭流
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}